import React from 'react';
import { Balloon } from '@teamix/ui';
import Empty from '../empty';
import './index.scss';
import intl from '../../../../../../../../locale';

const { Tooltip } = Balloon;

const labels = {
  init: intl.get({
    id: 'code-assets.containers.group-status.NotRunning',
    defaultMessage: '未运行',
  }),
  running: intl.get({
    id: 'code-assets.containers.group-status.Running',
    defaultMessage: '运行中',
  }),
  waiting: intl.get({
    id: 'code-assets.containers.group-status.Waiting',
    defaultMessage: '等待中',
  }),
  success: intl.get({
    id: 'code-assets.containers.group-status.RunSuccessfully',
    defaultMessage: '运行成功',
  }),
  fail: intl.get({ id: 'code-assets.containers.group-status.Failed', defaultMessage: '运行失败' }),
  canceled: intl.get({
    id: 'code-assets.containers.group-status.Canceled',
    defaultMessage: '已取消',
  }),
  cancelling: intl.get({
    id: 'code-assets.containers.group-status.Canceling',
    defaultMessage: '取消中',
  }),
};

const GroupStatus = ({ groups = [] }) => {
  const prefix = 'pipe-history';
  if (groups.length === 0) return <Empty />;
  const activeIndex =
    groups.length -
    1 -
    groups
      .slice()
      .reverse()
      .findIndex((g) => g.status.toLowerCase() !== 'init');
  const LENGTH = 4;
  const start = Math.max(0, activeIndex - 1);
  const end = activeIndex + (LENGTH - 1);
  const slices = groups.slice(start, end);
  if (slices.length < LENGTH) {
    const leftPadding = groups.slice(Math.max(0, start - (LENGTH - slices.length)), start);
    slices.unshift(...leftPadding);
    if (slices.length < LENGTH) {
      const rightPadding = groups.slice(end, end + (LENGTH - slices.length));
      slices.push(...rightPadding);
    }
  }

  return (
    <div className={prefix}>
      {slices.map((group, index) => {
        const groupStatus =
          group.status === 'FINISH' ? group.resultStatus.toLowerCase() : group.status.toLowerCase();

        const trigger = (
          <div className="content">
            <div className="title">{group.name}</div>
            <div className="point" />
          </div>
        );

        return (
          <div
            key={`${group.name}-${index}`}
            className={[
              'group-status',
              `group-status-${groupStatus} ${activeIndex === group.idx ? 'active' : ''}`,
              `${groups.length > group.idx + 1 && index === LENGTH - 1 ? 'has-more' : ''}`,
            ].join(' ')}
          >
            <Tooltip
              type="primary"
              trigger={trigger}
              align="t"
              offset={[0, 20]}
              popupProps={{ delay: 200 }}
            >
              {group.name}: {labels[groupStatus]}
            </Tooltip>
          </div>
        );
      })}
    </div>
  );
};

export default GroupStatus;
